package com.xm9m.web.service.controller;


import com.salesmanager.core.business.app.service.AppChannelService;
import com.salesmanager.core.business.customer.service.*;

import com.salesmanager.core.modules.jms.service.JmsService;
import com.salesmanager.core.modules.sms.SmsService;
import com.salesmanager.core.utils.CacheUtils;
import com.salesmanager.core.utils.CoreConfiguration;
import com.xm9m.web.service.api.response.common.SimpleResponse;
import com.xm9m.web.service.constants.StatusCode;
import com.xm9m.web.service.internal.util.BuildResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * Created by Liutong on 12/16/15.
 */
public abstract class AbstractRestApiController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRestApiController.class);
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    CustomerService customerService;

    @Autowired
     CoreConfiguration coreConfiguration;

    @Autowired
    CacheUtils cache;

    @Autowired
    JmsService jmsService;

    @Autowired
    protected SmsService smsService;

    @Autowired
    protected AppChannelService appChannelService;

    @Autowired
    protected CustomerAccountService customerAccountService;
    @Autowired
    protected CustomerAccountDetailsService customerAccountDetailsService;

    /**
     * 异常统一处理
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleException(Exception ex) {
        SimpleResponse errorResponse;
        if(ex instanceof AccessDeniedException) {
            errorResponse = BuildResponseUtil.buildSimpleResponse(StatusCode.USER_ERROR);
        } else {
            errorResponse = BuildResponseUtil.buildSimpleResponse(StatusCode.UNKNOWN_ERROR);
        }

        LOGGER.error(ex.getMessage(),ex);

        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        return new ModelAndView(jsonView,"error",errorResponse);
    }
}
